package com.dengyin2000.javaeye.ordering.action;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.core.Events;
import org.jboss.seam.faces.FacesMessages;

import com.dengyin2000.javaeye.ordering.entity.Dish;
import com.dengyin2000.javaeye.ordering.entity.DishOrder;
import com.dengyin2000.javaeye.ordering.entity.SnackShop;
import com.dengyin2000.javaeye.ordering.entity.User;

@Name("dishOrderAction")
public class DishOrderAction implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8433787210245818054L;
	
	@In(required=false) @Out(required=false)
	private SnackShop snackShop;
	
	@In("orderingDatabase")
	private Session session;
	
	private List<Dish> selectedDishes;
	
	@In(required=false) @Out(required=false)
	private DishOrder dishOrder;
	
	@In @Out(required=false)
	private User currentUser;
	
	@In
	private FacesMessages facesMessages;
	
	@In
	private Events events;
	
	private boolean alreadyOrdered;
	
	public boolean isAlreadyOrdered() {
		return alreadyOrdered;
	}
	
	@Begin(join=true)
	public void selectSnackShop(SnackShop shop) { 
		this.snackShop = (SnackShop) session.merge(shop);
	}

	public List<Dish> getSelectedDishes() {
		return selectedDishes;
	}

	public void setSelectedDishes(List<Dish> selectedDishes) {
		this.selectedDishes = selectedDishes;
	}
	
	public void orderDishes() {
		
		dishOrder = new DishOrder();
		dishOrder.getDishes().addAll(selectedDishes);

	}
		
   @End
   public void confirm(){
	   dishOrder.setCreateDate(new Date());
	   session.persist(dishOrder);
	   User u = (User) session.load(User.class, currentUser.getId());
	   u.getOrders().add(dishOrder);

	  dishOrder.setUser(u);
	  session.update(u);
      facesMessages.add("你已经订餐成功！");
      events.raiseTransactionSuccessEvent("orderConfirmed");
   }	
	
	@End
	public void cancel() {}

}
